<template>
  <a-card :bordered="false" style="overflow-x: auto;">
    <!-- 搜索选项框 -->
    <div :class="advanced ? 'search' : null">
      <a-form layout="horizontal">
        <div :class="advanced">
          <a-form-item label="ID" :labelCol="{ span: 7 }" :wrapperCol="{ span: 10 }">
            <a-input placeholder="Please input id" v-model="id" />
          </a-form-item>
        </div>
        <span style="float: right; margin-top: 3px">
          <a-button type="primary" @click="searchById">search</a-button>
        </span>
      </a-form>
    </div>
    <div>
      <!-- 新建和删除按钮 -->
      <a-space class="operator">
        <a-button @click="addNewUser" type="primary">new</a-button>
        <a-dropdown>
          <a-menu @click="handleMenuClick" slot="overlay">
            <a-menu-item key="delete">delete</a-menu-item>
            <a-menu-item key="audit">disable</a-menu-item>
          </a-menu>
          <a-button> actions <a-icon type="down" /> </a-button>
        </a-dropdown>
      </a-space>
      <!-- 图书列表 -->
      <standard-table
          :loading="loading"
          :columns="columns"
          :dataSource="dataSource"
          :selectedRows.sync="selectedRows"
          @clear="onClear"
          @change="onChange"
          @selectedRowChange="onSelectChange"
          :scroll="{ x: 1500 }"
      >
        <template #avatar="{ record }">
          <a-avatar :src="record.avatar" style="width: 50px; height: 50px" />
        </template>
        <template #qrcode="{ record }">
          <vue-qr :text="record.id" qid="testid" style="width: 100px; height: 100px" />
        </template>
        <template #action="{ record }">
          <a-dropdown :trigger="['click']">
            <a class="ant-dropdown-link" @click.prevent>
              actions <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item key="0">
                <router-link :to="`/admin/user/${record.key}/edit`">
                  <a-space>
                    <a-icon type="edit" />
                    <span>Edit</span>
                  </a-space>
                </router-link>
              </a-menu-item>
              <a-menu-item key="1">
                <router-link :to="`/admin/user/${record.key}/reservations`">
                  <a-space>
                    <a-icon type="search" />
                    <span>Reservations</span>
                  </a-space>
                </router-link>
              </a-menu-item>
              <a-menu-item key="2">
                <router-link :to="`/admin/user/${record.key}/borrowings`">
                  <a-space>
                    <a-icon type="search" />
                    <span>Borrowings</span>
                  </a-space>
                </router-link>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
        <template #statusTitle>
          <a-icon @click.native="onStatusTitleClick" type="info-circle" />
        </template>
      </standard-table>
    </div>
  </a-card>
</template>
<script>
import StandardTable from "@/components/table/StandardTable";
import VueQr from 'vue-qr';
import { getAccessToken } from '../../services/user';

const columns = [
  { title: "user_id", dataIndex: "key", width: 80 },
  { title: "avatar", dataIndex: "avatar", scopedSlots: { customRender: 'avatar' }, width: 80 },
  { title: "id", dataIndex: "id", width: 70 },
  { title: "name", dataIndex: "name", width: 100 },
  { title: "gender", dataIndex: "gender", width: 80 },
  { title: "email", dataIndex: "email", width: 120 },
  { title: "phone", dataIndex: "phone_number", width: 120 },
  { title: "borrow limit", dataIndex: "max_borrowing", width: 120 },
  { title: "Reputation Score", dataIndex: "reputation_score", width: 120 },
  { title: "actions", scopedSlots: { customRender: "action" }, width: 90 },
];

export default {
  name: "UserManage",
  components: { StandardTable, VueQr },
  data() {
    return {
      advanced: true,
      columns,
      dataSource: [],
      selectedRows: [],
      loading: true,
      id: ""
    };
  },
  methods: {
    deleteRecord(key) {
      this.dataSource = this.dataSource.filter(item => item.key !== key);
      this.selectedRows = this.selectedRows.filter(item => item.key !== key);
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    remove() {
      this.loading = true;
      const ids = this.selectedRows.map(row => row.key);

      const myHeaders = new Headers();
      myHeaders.append("token", getAccessToken());
      myHeaders.append("Content-Type", "application/json");

      const requestOptions = {
        method: 'DELETE',
        headers: myHeaders,
        body: JSON.stringify(ids),
      };

      fetch(`${this.$global.BASE_URL}/api/admin/user/delete`, requestOptions)
          .then(response => response.json())
          .then(result => {
            const { code, msg, data } = result;
            if (code === '0' || code === 0) {
              this.$message.success("Delete user successfully.");
              this.dataSource = this.dataSource.filter(
                  item => !this.selectedRows.some(row => row.key === item.key)
              );
            } else if (result.status == 500) {
              this.$message.error("Fail to delete users. Please contact the manager.");
            }
            this.selectedRows = [];
            this.loading = false;
          })
          .catch(error => {
            this.$message.error("API call failed");
            this.selectedRows = [];
            this.loading = false;
          });
    },
    onClear() {
      // this.$message.info("您清空了勾选的所有行");
    },
    onStatusTitleClick() {
      // this.$message.info("你点击了状态栏表头");
    },
    onChange() {
      // this.$message.info("表格状态改变了");
    },
    onSelectChange() {
      // this.$message.info("选中行改变了");
    },
    addNewUser() {
      this.$router.push("/admin/user/add").catch((err) => {
        console.log("跳转useradd报错", err);
      });
    },
    handleMenuClick(e) {
      if (e.key === "delete") {
        this.remove();
      }
    },
    searchById() {
      const id = this.id.toString();
      this.dataSource = this.dataSource.filter(item => item.id === id);
    }
  },
  created() {
    this.loading = true;
    const myHeaders = new Headers();
    myHeaders.append("token", getAccessToken());

    const requestoptions = {
      method: "GET",
      headers: myHeaders,
    };

    fetch(`${this.$global.BASE_URL}/api/admin/user/getAll?page_size=100&current_page=1`, requestoptions)
        .then(response => response.json())
        .then(result => {
          console.log(result);
          if (result.code == 0 || result.code == "0") {
            this.dataSource = result.data.slice(1).map(i => ({
              key: i.userId,
              avatar: i.avatar,
              id: i.id,
              name: i.name,
              gender: i.gender,
              email: i.email,
              phone_number: i.phoneNumber,
              max_borrowing: 20,
              reputation_score: i.reputationScore,
            }));
            this.loading = false;
          } else {
            this.$message.error("API call failed.");
            this.loading = false;
          }
        })
        .catch(error => {
          this.$message.error("API call failed.");
          this.loading = false;
        });
  },
};
</script>
<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}
.fold {
  width: calc(100% - 216px);
  display: inline-block;
}
.operator {
  margin-bottom: 18px;
}

@media screen and (max-width: 900px) {
.fold {
  width: 100%;
  }
}
</style>
